package xyz.zdsoft.personal_info_madule.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xyz.zdsoft.common.exception.BizException;
import xyz.zdsoft.common.utils.JwtUtils;
import xyz.zdsoft.common.utils.Result;
import xyz.zdsoft.common.utils.ResultBody;
import xyz.zdsoft.personal_info_madule.mapper.StudentInfoMapper;
import xyz.zdsoft.personal_info_madule.service.StudentInfoService;
import xyz.zdsoft.personal_info_madule.vo.ClassHourOfTeamVo;
import xyz.zdsoft.personal_info_madule.vo.ProjectScoreVo;
import xyz.zdsoft.personal_info_madule.vo.StuInfoVo;
import xyz.zdsoft.personal_info_madule.vo.TeamRank;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class StudentInfoServiceImpl implements StudentInfoService {

    @Value("${logoFile}")
    private String logoFile;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Override
    public Result<StuInfoVo> queryStuInfo() {
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        return Result.ok().data(studentInfoMapper.queryStuInfo(stuId));
    }

    @Override
    public ResultBody fileDelAndUpdate(String newPath) {
        int uid;
        try {
            uid = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        Map<String, String> updateInfo = studentInfoMapper.queryCurNoAndLogo(uid);
        File f = new File(logoFile + updateInfo.get("logo_url"));
        if (f.exists()) {
            f.delete();
        }
        if (studentInfoMapper.changeFace(newPath,
                updateInfo.get("user_no") + updateInfo.get("name"), uid) >= 1) {
            return ResultBody.success();
        }
        new File(newPath).delete();
        return ResultBody.error("上传头像失败");
    }

    @Override
    public ResultBody changeEmail(String email) {
        if (StringUtils.isBlank(email)) {
            return ResultBody.error("邮箱不能为空");
        }

        if (!Pattern.matches(
                "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$",
                email)) {
            return ResultBody.error("邮箱格式错误");
        }
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        if (studentInfoMapper.changeEmail(email, stuId) >= 1) {
            return ResultBody.success();
        }
        return ResultBody.error("修改邮箱失败");
    }

    @Override
    public ResultBody changePhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return ResultBody.error("电话号码不能为空");
        }

        if (!Pattern.matches(
                "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$",
                phone)) {
            return ResultBody.error("电话号码格式错误");
        }
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        if (studentInfoMapper.changePhone(phone, stuId) >= 1) {
            return ResultBody.success();
        }
        return ResultBody.error("修改电话号码失败");
    }


    @Override
    public Result<ClassHourOfTeamVo> queryTeamClassHour() {
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        return Result.ok().data(studentInfoMapper.queryTeamClassHour(stuId));
    }

    @Override
    public Result<ProjectScoreVo> queryTeamScoreForCou() {
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        List<ProjectScoreVo> projectScoreVos = studentInfoMapper.queryTeamScoreForCou(stuId);
        for (ProjectScoreVo projectScoreVo : projectScoreVos) {
            if (studentInfoMapper.isScoreOfCouTeam(projectScoreVo.getCourseId()) > 0) {
                projectScoreVo.setRank(studentInfoMapper.queryTeamRank(projectScoreVo.getCourseId(),
                        projectScoreVo.getTeamId()).get(0).getRowno());
            } else {
                projectScoreVo.setRank(0);
            }
        }
        return Result.ok().data(projectScoreVos);
    }

    @Override
    public Result<TeamRank> queryTeamRank(Integer couId) {
        if (studentInfoMapper.isScoreOfCouTeam(couId) <= 0) {
            throw new BizException("课程中小组评分未完成, 不能查看排名");
        }
        return Result.ok().data(studentInfoMapper.queryTeamRank(couId, null));
    }
}
